import React, {useEffect, useRef} from 'react';
import {connect} from 'dva';
import './index.less';
import {Button, Select, Table, Tag, Tooltip} from 'antd';
import {
  PlusCircleOutlined,
  InfoCircleOutlined,
  EditOutlined,
  DeleteOutlined,
  ExperimentOutlined,
  UpCircleOutlined, UnlockOutlined, WifiOutlined, LockOutlined, DownCircleOutlined, ApiOutlined,
} from '@ant-design/icons';
import moment from 'moment';
import {useState} from 'react';
import AddApi from './components/AddApi';
import apiManage from "@/models/apiManage";
import GroupModal from "@/pages/components/GroupModal";
import {save} from "@/utils/blob2file";
import ApiInfoModal from "@/pages/components/ApiInfoModal";
import TestModal from "@/pages/components/TestMoal";
import TokenModal from "@/pages/components/TokenModal";
import UploadPlugin from "@/pages/components/UploadPlugin";

const ApiManage = props => {
  const {Option} = Select;
  const {
    apiManage: {},
    dispatch,
  } = props;
  const [apiData, setApiData] = useState([]);
  const [exportType, setExportType] = useState('');
  const [importType, setImportType] = useState('');
  const [info_id, setInfo_id] = useState('');
  const [infoVis, setInfoVis] = useState(false);
  const [reqPrefix, setReqPrefix] = useState('');
  const [testVis, setTestVis] = useState(false);
  const [testApi, setTestApi] = useState({});
  const [tokenModal, setTokenModal] = useState(false);
  const [token, setToken] = useState('');
  const onSelectOut = (val) => {
    setExportType(val);
  };
  const onSelectIn = (val) => {
    setImportType(val);
  };
  const [addModalVisible, setAddModalVisible] = useState(false);
  const [groupModalVisible, setGroupModalVisible] = useState(false);
  const [uploadPluginVis, setUploadPluginVis] = useState(false);

  function paramsGroup(params) {
    if (params === null) return ;
    return params.map((item) => {
      return (
        <Tag color={"geekblue"} key={item}>
          {item.name + "|" + item.type}
        </Tag>
      );
    })
  }

  function statusBlock(record) {
    return (
      <>
        {record.status === 0 ? <WifiOutlined style={{color: "red"}}/> : <WifiOutlined style={{color: "green"}}/>}
        {record.previlege !== 0 ? <UnlockOutlined style={{color: "green"}}/> : <LockOutlined style={{color: "red"}}/>}
      </>
    )
  }

  function handleApiInfo(api_id) {
    setInfo_id(api_id);
    setInfoVis(true);
  }

  function handleUp(api_id) {
    dispatch({
      type: "apiManage/online",
      payload: {
        id: api_id
      }
    }).then(() => {
      getAllApiConfigInfo();
    });
  }

  function handleDown(api_id) {
    dispatch({
      type: "apiManage/offline",
      payload: {
        id: api_id
      }
    }).then(() => {
      getAllApiConfigInfo();
    });
  }

  function handleTest(api) {
    setTestApi(api);
    setTestVis(true);
  }

  function getToken(id) {
    dispatch({
      type: "apiManage/getToken",
      payload: {
        groupId: id
      }
    }).then(res => {
      setToken(res);
      setTokenModal(true);
    })
  }

  function handleDel(id) {
    dispatch({
      type: "apiManage/del",
      payload: {
        id: id
      }
    }).then(res => {
      getAllApiConfigInfo();
    });
  }

  const columns = [
    {
      title: 'API-ID',
      dataIndex: 'id',
      key: 'id'
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <>
          {record.status === 0 ? <WifiOutlined style={{color: "red"}}/> : <WifiOutlined style={{color: "green"}}/>}
          {record.previlege !== 0 ? <UnlockOutlined style={{color: "green"}}/> : <LockOutlined style={{color: "red"}}/>}
          {text}
        </>
      )
    },
    {
      title: 'Token',
      dataIndex: 'token',
      key: 'token',
      render: (text, record) => (
        <ApiOutlined style={{color: "blue"}} onClick={() => {
          getToken(record.groupId)
        }}/>
      )
    },
    {
      title: '描述信息',
      dataIndex: 'note',
      key: 'note'
    },
    {
      title: '路径',
      dataIndex: 'path',
      key: 'path'
    },
    {
      title: '参数',
      dataIndex: 'params',
      key: 'params',
      render: (text) => (
        <>
          {paramsGroup(JSON.parse(text))}
        </>
      )
    },
    {
      title: '修改时间',
      key: 'updateTime',
      dataIndex: 'updateTime',
      width: '200px',
      // render: text => moment(text).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '操作',
      key: 'operation',
      render: (text, record) => (
        <div>
          <Tooltip placement="top" title="详细信息">
            <InfoCircleOutlined className="oper-icon" style={{color: '#23d346'}}
                                onClick={() => handleApiInfo(record.id)}/>
          </Tooltip>
          {/*<Tooltip placement="top" title="编辑">*/}
          {/*  <EditOutlined className="oper-icon" style={{color: '#1890ff'}}/>*/}
          {/*</Tooltip>*/}
          {record.status === 0 ? <Tooltip placement="top" title="上线">
            <UpCircleOutlined className="oper-icon" style={{color: '#1890ff'}} onClick={() => handleUp(record.id)}/>
          </Tooltip> : <Tooltip placement="top" title="下线">
            <DownCircleOutlined className="oper-icon" style={{color: '#1890ff'}} onClick={() => handleDown(record.id)}/>
          </Tooltip>}

          {record.status === 1 &&
          <Tooltip placement="top" title="测试">
            <ExperimentOutlined className="oper-icon" onClick={() => {
              handleTest(record)
            }}/>
          </Tooltip>
          }
          {record.status === 0 &&
          <Tooltip placement="top" title="删除">
            <DeleteOutlined className="oper-icon" style={{color: 'red'}} onClick={() => {
              handleDel(record.id)
            }}/>
          </Tooltip>}
        </div>
      ),
    },
  ];
  const data = [
    {
      id: 11111111111111111,
      name: 'zhang',
      path: '/api/test',
      parameter: 'this is xiaozhang',
      updateTime: 11111111111,
    },
    {
      id: 11111111111111111,
      name: 'zhang',
      path: '/api/test',
      parameter: 'this is xiaozhang',
      updateTime: 11111111111,
    },
  ];
  const handleAddApi = () => {
    setAddModalVisible(true);
  };

  function getApiGroupInfo() {

  }

  const handleClickGroup = () => {
    console.log('enter');
    setGroupModalVisible(true);
  };

  function getAllApiConfigInfo() {
    dispatch({
      type: "apiManage/getAllApiConfigInfo"
    }).then(res => {
      console.log("apis", res);
      setApiData(res);
      dispatch({
        type: "apiManage/getIPPort"
      }).then(res => {
        setReqPrefix("http://" + res + "/api/");
      });
    });
  }

  //
  useEffect(() => {
    console.log("组件加载时，运行一次该函数");
    getAllApiConfigInfo();
  }, []);

  function exportConfig() {
    let type = '';
    let filename = '';
    switch (exportType) {
      case 'file': {
        type = 'apiManage/apiDocs';
        filename = 'api文档.md';
        break;
      }
      case 'api': {
        type = 'apiManage/downloadConfig';
        filename = 'apiconfig.json';
        break;
      }
      default: {
        type = 'apiManage/downloadGroupConfig';
        filename = 'group.json';
      }
    }
    dispatch({
      type: type
    }).then(res => {
      save(res, filename);
    });
  }

  function handleImport() {
    // TODO:
  }

  function uploadPlugin() {
    setUploadPluginVis(true);
  }

  return (
    <div className="api-manage">
      <h2 className="big-font">API面板</h2>
      <div style={{marginBottom: '20px'}}>
        <Button className="btns" onClick={handleAddApi}>
          <PlusCircleOutlined style={{marginLeft: '-8px'}}/>
          创建API
        </Button>
        <Button className="btns" onClick={handleClickGroup}>
          API分组管理
        </Button>

        {/*<Select defaultValue="lucy" style={{ width: 120 }} onChange={handleChange}> */}
        <Select className="selects" placeholder="选择导出内容" onChange={onSelectOut}>
          <Option value="file">API文档</Option>
          <Option value="api">API</Option>
          <Option value="group">API分组</Option>
        </Select>

        <Button className="btns" onClick={exportConfig}>导出</Button>
        <Button className="btns" onClick={uploadPlugin}>上传插件</Button>

        {/*<Select className="selects" placeholder="选择导入内容" onChange={onSelectIn} >*/}
        {/*  <Option value="api">API</Option>*/}
        {/*  <Option value="group">API分组</Option>*/}
        {/*</Select>*/}

        {/*<Button className="btns" onClick={handleImport}>导入</Button>*/}
      </div>
      {addModalVisible && <AddApi setAddModalVisible={setAddModalVisible} addModalVisible={addModalVisible}
                                  getAllApiConfigInfo={getAllApiConfigInfo} apiManage={apiManage} dispatch={dispatch} prefix={reqPrefix}/>}
      {groupModalVisible &&
      <GroupModal visible={groupModalVisible} setVisible={setGroupModalVisible} dispatch={dispatch}/>}

      {infoVis && <ApiInfoModal visible={infoVis} setVisible={setInfoVis} api_id={info_id} dispatch={dispatch}/>}
      {testVis &&
      <TestModal vis={testVis} setVis={setTestVis} api={testApi} dispatch={dispatch} prefixPath={reqPrefix}/>}
      {tokenModal && <TokenModal vis={tokenModal} setVis={setTokenModal} token={token}/>}
      {uploadPluginVis && <UploadPlugin vis={uploadPluginVis} setVis={setUploadPluginVis} dispatch={dispatch}/>}

      <Table title={() => {
        return (
          <h3 align="center" style={{color: "#1890ff"}}>{"API请求前缀:\t" + reqPrefix}</h3>

        )
      }} columns={columns} dataSource={apiData}/>
    </div>
  );
};

export default connect(({apiManage}) => ({apiManage}))(ApiManage);
